//
//  InformationViewController.m
//  时尚男士
//
//  Created by Jupiter on 15/6/3.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "InformationViewController.h"
#import "AFNetworking.h"
#import "InformationCell.h"
#import "UIImageView+AFNetworking.h"
#import "InfoDetailController.h"
#import "Information_ImgLab.h"
#import "FirstCell.h"
#import "ShowCell.h"
#import "InfoPhotoViewController.h"
#import "Photo.h"

#define CELLIDENTFIER @"reuse"
#define HEIGHT (self.view.frame.size.height / 3)
#define WIDTH (self.view.frame.size.width - 10)
@interface InformationViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableDictionary *dic;
@property (nonatomic, retain) NSMutableArray *arr;

@end

@implementation InformationViewController

//数据处理
- (void)dataHandle
{
    NSString *str = [NSString stringWithFormat: @"http://c.m.163.com/nc/article/list/T1348650593803/0-20.html"];
    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *html = operation.responseString;
        NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];
        id dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        //NSLog(@"获取到的数据为:%@", dict);
        self.dic = dict;
        self.arr = [dict objectForKey:@"T1348650593803"];
        NSLog(@"获取的数据:%@", self.arr);
        [_tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"发生错误:%@", error);
    }];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation];

    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self dataHandle];
    
    self.user = [NSUserDefaults standardUserDefaults];
    self.navigationController.navigationBar.translucent = NO;
    
    //添加加载
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.removeFromSuperViewOnHide = YES;
    self.hud.labelText = @"加载中";
    self.hud.mode = MBProgressHUDModeIndeterminate;
    
    //添加背景
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.jpg"]];
    if ([self.user boolForKey:@"name"]) {
        
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.jpg"]];
    }else{
        
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg1.jpg"]];
    }
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(receiveNoficiation:) name:@"name" object:nil];

    
    //扩展tableview
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(5, 0, WIDTH, HEIGHT * 3 - 64 - 49) style:UITableViewStylePlain];
    //*3 - 64
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView .dataSource = self;
    [self.view addSubview:_tableView];
    self.hud.hidden = YES;
    //[_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CELLIDENTFIER];
    [_tableView release];
}
//设置tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (indexPath.row == 0) {
//        //第一行的cell
//        FirstCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellReuse"];
//        cell = [[FirstCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cellReuse"];
//        [cell.firstImageView setImageWithURL:[NSURL URLWithString:[[self.arr objectAtIndex:0] objectForKey:@"imgsrc"]]];
//        cell.firstLabel.text = [[self.arr objectAtIndex:0] objectForKey:@"title"];
//        //[cell firstButton];
//        return cell;
//    }
    
        if([[[self.arr objectAtIndex:indexPath.row] allKeys] containsObject:@"imgextra"]) {
            ShowCell *cell = [tableView dequeueReusableCellWithIdentifier:@"showReuse"];
            if (!cell) {
                cell = [[[ShowCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"showReuse"] autorelease];
            }
            cell.backgroundColor = [UIColor clearColor];
            [cell.showImageView1 setImageWithURL:[NSURL URLWithString:[[[[self.arr objectAtIndex:indexPath.row] objectForKey:@"imgextra"] objectAtIndex:0] objectForKey:@"imgsrc"]]];
            //NSLog(@"%@", [self.arr objectAtIndex:indexPath.row]);
            [cell.showImageView2 setImageWithURL:[NSURL URLWithString:[[[[self.arr objectAtIndex:indexPath.row]objectForKey:@"imgextra"] objectAtIndex:1] objectForKey:@"imgsrc"]]];
            [cell.showImageView3 setImageWithURL:[NSURL URLWithString:[[self.arr objectAtIndex:indexPath.row] objectForKey:@"imgsrc"]]];
            cell.showLabel.text = [[self.arr objectAtIndex:indexPath.row] objectForKey:@"title"];
            
            return cell;
        } else {
            InformationCell *cell = [tableView dequeueReusableCellWithIdentifier:CELLIDENTFIER];
            if (!cell) {
                cell = [[InformationCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CELLIDENTFIER];
            }
            cell.backgroundColor = [UIColor clearColor];
            [cell.infoImageView setImageWithURL:[NSURL URLWithString:[[self.arr objectAtIndex:indexPath.row] objectForKey:@"imgsrc"]]];
            //cell.imageView.image = [UIImage imageNamed:@"3.jpg"];
            cell.infoTitle.text = [[self.arr objectAtIndex:indexPath.row] objectForKey:@"title"];
            cell.infoDigest.text = [[self.arr objectAtIndex:indexPath.row] objectForKey:@"digest"];
            return cell;
        }
        

    return nil;
    
}

//文字高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    //指定第一行cell
//    if (indexPath.row == 0) {
//        return HEIGHT ;
//    }
    
    if (indexPath.row >= 0 && indexPath.row <= self.arr.count) {
    
        if ([[[self.arr objectAtIndex:indexPath.row] allKeys] containsObject:@"imgextra"]) {
            NSString *text = [[self.arr objectAtIndex:indexPath.row] objectForKey:@"title"];
            NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
            CGRect rect = [text boundingRectWithSize:CGSizeMake(tableView.frame.size.width, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
            return rect.size.height + 70;
        }
        
        //1.取得要计算的字符串
        NSString *text = [[self.arr objectAtIndex:indexPath.row] objectForKey:@"title"];
        //2.计算高度
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
        CGRect rect = [text boundingRectWithSize:CGSizeMake(tableView.frame.size.width, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return rect.size.height + 70;
    }
    return 1000;
}

//点击推出下一页
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.row) {
        InfoPhotoViewController *photo = [[InfoPhotoViewController alloc] init];
        photo.photoUrl = [[self.arr objectAtIndex:indexPath.row] objectForKey:@"imgsrc"];
        [self.navigationController pushViewController:photo animated:YES];
        [photo release];
    } else if ([[[self.arr objectAtIndex:indexPath.row] allKeys] containsObject:@"imgextra"]) {
        Photo *infoPhoto = [[Photo alloc] init];
        infoPhoto.photoUrl = [[self.arr objectAtIndex:indexPath.row] objectForKey:@"imgsrc"];
        infoPhoto.photoLabel = [[self.arr objectAtIndex:indexPath.row] objectForKey:@"digest"];
        infoPhoto.photoImg1 = [[[[self.arr objectAtIndex:indexPath.row] objectForKey:@"imgextra"] objectAtIndex:0] objectForKey:@"imgsrc"];
        infoPhoto.photoImg2 = [[[[self.arr objectAtIndex:indexPath.row] objectForKey:@"imgextra"] objectAtIndex:1] objectForKey:@"imgsrc"];
        [self.navigationController pushViewController:infoPhoto animated:YES];
        [infoPhoto release];
    } else {
    
    InfoDetailController *infoDetailVC = [[InfoDetailController alloc] init];
    infoDetailVC.Docid = [[self.arr objectAtIndex:indexPath.row] objectForKey:@"url_3w"];
    [self.navigationController pushViewController:infoDetailVC animated:YES];
    [infoDetailVC release];
    }
}

- (void)receiveNoficiation:(NSNotification *)noti{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([user boolForKey:@"name"]) {
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.jpg"]];
        NSLog(@"改变背景");
    }else{
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg1.jpg"]];
    }
}

- (void)dealloc
{
    [_tableView release];
    [_arr release];
    [_dic release];
    [_user release];
    [_hud release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
